package com.dqhl.community.activity;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.dqhl.community.R;
import com.dqhl.community.adapter.ExchangeCouponAdapter;
import com.dqhl.community.adapter.PayMentCouponAdapter;
import com.dqhl.community.base.BaseActivity;
import com.dqhl.community.model.ExchangeCoupon;
import com.dqhl.community.model.PayMentCoupon;
import com.dqhl.community.util.Config;
import com.dqhl.community.util.Constant;
import com.dqhl.community.util.Dlog;
import com.dqhl.community.util.DoubleOperation;
import com.dqhl.community.util.JsonUtils;
import com.dqhl.community.wxpay.WxPaymentUtils;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.List;

/**
 * Created by Administrator on 2016/9/6.
 * 商品支付页面
 */
public class ShoppingPaymentActivity extends BaseActivity implements View.OnClickListener {

    private Context context;
    private ImageView mIvback;
    private TextView mTvTitle;
    private TextView mTvAllMoney;//总支付金额
    private TextView tv_price; //图片旁边的单价
    private TextView mTvNumber;//购买数量
    private TextView tv_name; //商品名称
    private ImageView iv_picture; //商品图片
    private ImageView mImOperation;
    private ImageView mImAdd;//加号
    private ImageView mImJian;//减号
    private TextView mTvAccount;//结算按钮
    private LinearLayout ll_add_gouwuche; //加入购物车
    private int num = 1;//商品个数
    private String strGoodsId; //商品id
    private String strPrice;
    private RadioGroup radioGroup;
    private RadioButton rb_weixin;
    private RadioButton rb_alipay;
    private RadioButton rb_cash;
    private String payment_method = ""; //支付方式

    private int totalNum; //最后提交的数量
    private String totalMoney;

    private String orderId;//订单号
    private String totalFee;//订单价格
    private String productInfo;//订单详情
    private TextView tv_address;
    private ListView lv_payment;
    private ListView lv_exchange;
    private String userId;
    private PayMentCouponAdapter payMentCouponAdapter;
    private List<PayMentCoupon> payMentCouponList;
    private ExchangeCouponAdapter exchangeCouponAdapter;
    private List<ExchangeCoupon> exchangeCouponList;
    private TextView tv_current_integral;
    private double tempMoney1;
    private double tempMoney2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shopping_payment);
        context = this;
        initView();
        getData();
        getCoupon();
        getExchangeCoupon();
    }

    /**
     * 获取数据
     */
    private void getData() {
        userId = user.getUserid();
        tv_current_integral.setText(user.getIntegral());
        tempMoney2 = tempMoney1 = Double.parseDouble(getIntent().getStringExtra("total_money"));
        String strAddress = user.getCommunity_id() + user.getBuilding_id() + user.getUnit_id() + user.getResidence_id();
        tv_address.setText(strAddress);
        String strMoney = getIntent().getStringExtra("total_money");
        int strNum = getIntent().getIntExtra("number", 1);
        String strName = getIntent().getStringExtra("name");
        String strImg = getIntent().getStringExtra("img");
        strGoodsId = getIntent().getStringExtra("goods_id");
        strPrice = getIntent().getStringExtra("price");

        tv_price.setText("￥" + strPrice);
        mTvAllMoney.setText("￥" + strMoney);
        num = strNum;
        totalNum = num;
        mTvNumber.setText(num + "");
        tv_name.setText(strName);
        Log.d("ShoppingPayment", "strImg=" + strImg);
        x.image().bind(iv_picture, Config.Api.base_img_url + strImg);
//        if(TextUtils.isEmpty(strImg)){
//            Log.d("ShoppingPaymentActivity","strImg="+strImg);
//            iv_picture.setImageResource(R.drawable.ic_bar_1);
//        }
        totalMoney = strMoney;
        if (num == 0) {
            mImJian.setVisibility(View.GONE);
        }
    }

    private void initView() {
        mIvback = (ImageView) findViewById(R.id.iv_top_back);
        mTvTitle = (TextView) findViewById(R.id.tv_top_title);
        tv_price = (TextView) findViewById(R.id.tv_price);
        mTvAllMoney = (TextView) findViewById(R.id.tv_shopping_allmoney);
        mImOperation = (ImageView) findViewById(R.id.tv_top_operation);
        mImAdd = (ImageView) findViewById(R.id.iv_account_jia);
        mImJian = (ImageView) findViewById(R.id.iv_account_jian);
        mTvNumber = (TextView) findViewById(R.id.tv_account_number);
        mTvAccount = (TextView) findViewById(R.id.tv_account);
        tv_name = (TextView) findViewById(R.id.tv_name);
        iv_picture = (ImageView) findViewById(R.id.iv_picture);
        radioGroup = (RadioGroup) findViewById(R.id.radioGroup);
        rb_weixin = (RadioButton) findViewById(R.id.rb_weixin);
        rb_alipay = (RadioButton) findViewById(R.id.rb_alipay);
        rb_cash = (RadioButton) findViewById(R.id.rb_cash);
        ll_add_gouwuche = (LinearLayout) findViewById(R.id.ll_add_gouwuche);
        tv_address = (TextView) findViewById(R.id.tv_address);
        lv_payment = (ListView) findViewById(R.id.lv_payment);
        lv_exchange = (ListView) findViewById(R.id.lv_exchange);
        tv_current_integral = (TextView) findViewById(R.id.tv_current_integral);

        mIvback.setVisibility(View.VISIBLE);
        mImOperation.setVisibility(View.INVISIBLE);
        mIvback.setOnClickListener(this);
        mImAdd.setOnClickListener(this);
        mImJian.setOnClickListener(this);
        mTvAccount.setOnClickListener(this);
        ll_add_gouwuche.setOnClickListener(this);
        mTvTitle.setText("在线超市");

        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                switch (i) {
                    case R.id.rb_weixin:
                        payment_method = "1";
                        break;
                    case R.id.rb_alipay:
                        payment_method = "1";
                        break;
                    case R.id.rb_cash:
                        payment_method = "2";
                        break;
                }
            }
        });
    }

    /**
     * 优惠券接口
     */
    private void getCoupon() {
        Dlog.e(userId);
        showCustomLoadBar("加载中");
        RequestParams params = new RequestParams(Config.Api.lookupCoupon);
        params.addBodyParameter("userid", userId);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Dlog.e("GG优惠券" + result);
                int errCode = JsonUtils.getErrCode(result);
                String data = JsonUtils.getInfo(result, "data");
                if (errCode == 0) {
                    payMentCouponList = JSON.parseArray(data, PayMentCoupon.class);
                    Dlog.e(payMentCouponList.toString());
                    (payMentCouponAdapter) = new PayMentCouponAdapter(context, payMentCouponList,
                            new PayMentCouponAdapter.OnRadioButtonCheckedListener() {
                                @Override
                                public void onSelectedPosition(int positon) {
                                    Dlog.e("selected:" + positon);
                                    tempMoney1 = Double.parseDouble(getIntent().getStringExtra("price"));
                                    if ("1".equals(payMentCouponList.get(positon).getCondition())) {
                                        Double deno = Double.parseDouble(payMentCouponList.get(positon).getDeno().replace("元", ""));
                                        Double denomination = Double.parseDouble(payMentCouponList.get(positon).getDenomination().substring(1, payMentCouponList.get(positon).getDenomination().length() - 1));
                                        Dlog.e("deno=" + deno + ";denomination:" + denomination);

                                        Double money = tempMoney1;
                                        if (money >= denomination) {
                                            money = money - deno;
                                        }
                                        tempMoney2 = money;
                                        totalMoney = String.valueOf(money);
                                        mTvAllMoney.setText("￥" + totalMoney);
                                    } else if ("2".equals(payMentCouponList.get(positon).getCondition())) {
                                        Double deno = Double.parseDouble(payMentCouponList.get(positon).getDeno().replace("折", ""));
                                        Dlog.e("deno=" + deno);
                                        Double money = tempMoney1;
                                        money = DoubleOperation.div(DoubleOperation.mul(money, deno), 10.0, 1);
                                        tempMoney2 = money;
                                        totalMoney = String.valueOf(money);
                                        mTvAllMoney.setText("￥" + totalMoney);
                                    } else if ("3".equals(payMentCouponList.get(positon).getCondition())) {
                                        Double deno = Double.parseDouble(payMentCouponList.get(positon).getDeno().replace("元", ""));
                                        Dlog.e("deno=" + deno);
                                        Double money = tempMoney1;
                                        money = money - deno;
                                        totalMoney = String.valueOf(money);
                                        tempMoney2 = money;
                                        mTvAllMoney.setText("￥" + totalMoney);
                                    }
                                }

                                @Override
                                public void onUnSelectedPosition(int positon) {
                                    Dlog.e("unselected:" + positon);
                                    tempMoney2 = tempMoney1;
                                    totalMoney = String.valueOf(tempMoney1);
                                    mTvAllMoney.setText("￥" + totalMoney);
                                }
                            });
                    payMentCouponAdapter.notifyDataSetChanged();
                    lv_payment.setAdapter(payMentCouponAdapter);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                hideCustomLoadBar();
            }
        });
    }

    private void getExchangeCoupon() {
        RequestParams params = new RequestParams(Config.Api.lookupExchange);
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Dlog.e(result);
                int errCode = JsonUtils.getErrCode(result);
                String data = JsonUtils.getInfo(result, "data");
                if (0 == errCode) {
                    exchangeCouponList = JSON.parseArray(data, ExchangeCoupon.class);
                    exchangeCouponAdapter = new ExchangeCouponAdapter(context, exchangeCouponList,
                            new ExchangeCouponAdapter.OnRadioButtonCheckedListener() {
                                @Override
                                public void onSelectedPosition(int positon) {
                                    Dlog.e("selected:" + positon);
                                    if ("1".equals(payMentCouponList.get(positon).getCondition())) {
                                        Double deno = Double.parseDouble(payMentCouponList.get(positon).getDeno().replace("元", ""));
                                        Double denomination = Double.parseDouble(payMentCouponList.get(positon).getDenomination().substring(1, payMentCouponList.get(positon).getDenomination().length() - 1));
                                        Dlog.e("deno=" + deno + ";denomination:" + denomination);
                                        Double money = tempMoney2;
                                        if (money >= denomination) {
                                            money = money - deno;
                                        }
                                        totalMoney = String.valueOf(money);
                                        mTvAllMoney.setText("￥" + totalMoney);
                                    } else if ("2".equals(payMentCouponList.get(positon).getCondition())) {
                                        Double deno = Double.parseDouble(payMentCouponList.get(positon).getDeno().replace("折", ""));
                                        Dlog.e("deno=" + deno);
                                        Double money = tempMoney2;
                                        money = DoubleOperation.div(DoubleOperation.mul(money, deno), 10.0, 1);
                                        totalMoney = String.valueOf(money);
                                        mTvAllMoney.setText("￥" + totalMoney);
                                    } else if ("3".equals(payMentCouponList.get(positon).getCondition())) {
                                        Double deno = Double.parseDouble(payMentCouponList.get(positon).getDeno().replace("元", ""));
                                        Dlog.e("deno=" + deno);
                                        Double money = tempMoney2;
                                        money = money - deno;
                                        totalMoney = String.valueOf(money);
                                        mTvAllMoney.setText("￥" + totalMoney);
                                    }
                                }

                                @Override
                                public void onUnSelectedPosition(int positon) {
                                    Dlog.e("unselected:" + positon);
                                    totalMoney = String.valueOf(tempMoney2);
                                    mTvAllMoney.setText("￥" + totalMoney);
                                }
                            });
                    exchangeCouponAdapter.notifyDataSetChanged();
                    lv_exchange.setAdapter(exchangeCouponAdapter);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    @Override
    public void onClick(View view) {

        double price = Double.valueOf(strPrice);
        switch (view.getId()) {
            case R.id.iv_top_back:
                finish();
                break;
            case R.id.iv_account_jia:
                totalNum = ++num;
                totalMoney = String.valueOf(price * totalNum);
                mTvNumber.setText(totalNum + "");
                mTvAllMoney.setText("￥" + totalMoney);
                mImJian.setVisibility(View.VISIBLE);
                break;
            case R.id.iv_account_jian:
                if (num > 0) {
                    totalNum = --num;
                    totalMoney = String.valueOf(price * totalNum);
                    mTvNumber.setText(totalNum + "");
                    mTvAllMoney.setText("￥" + totalMoney);
                    if (num == 0) {
                        mImJian.setVisibility(View.GONE);
                    }
                }
                break;
            case R.id.tv_account:
                doSubmit();
                break;
            case R.id.ll_add_gouwuche:
                addShopCart();
                break;
        }
    }

    /**
     * 添加到购物车
     */
    private void addShopCart() {
        if (totalNum == 0) {
            toast("请选择商品数量！");
        } else {
            showCustomLoadBar(R.string.loading);
            Dlog.e(spUserInfo.getString(Constant.USERID, "") + "GG" + strGoodsId + " *** " + totalNum);
            RequestParams parms = new RequestParams(Config.Api.addShopCart);
            parms.addBodyParameter("good_id", strGoodsId);
            parms.addBodyParameter("userid", spUserInfo.getString(Constant.USERID, ""));
            parms.addBodyParameter("number", totalNum + "");
            x.http().post(parms, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    int errCode = JsonUtils.getErrCode(result);
                    Dlog.e("GG添加购物车返回的数据" + result);
                    if (errCode == 0) {
                        toast("加入成功！");
                        finish();
                    } else {
                        toast("加入失败");
                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    toast(R.string.error_net_connection);
                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {
                    hideCustomLoadBar();
                }
            });
        }
    }

    /**
     * 立即结算
     */
    private void doSubmit() {
        if (totalNum == 0) {
            toast("请选择商品数量");
        } else if ("".equals(payment_method) || payment_method.length() <= 0) {
            toast("请选择支付方式");
        } else {
            Dlog.e("提交的数据：" + app.getUserId() + ";" + strGoodsId + ";" + totalMoney + ";"
                    + payment_method + ";" + totalNum);
            showCustomLoadBar("正在提交…");
            RequestParams params = new RequestParams(Config.Api.supermarketsell);
            params.addBodyParameter("good_id", strGoodsId);
            params.addBodyParameter("userid", app.getUserId());
            params.addBodyParameter("total", totalMoney);
            params.addBodyParameter("payment_method", payment_method);
            params.addBodyParameter("number", totalNum + "");
            x.http().post(params, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    Dlog.e(result);
                    int errCode = JsonUtils.getErrCode(result);
                    String data = JsonUtils.getInfo(result, "data");
//                    overlay(DistributionDetailActivity.class);
                    if (errCode == 0) {
                        orderId = JsonUtils.getInfo(data, "order_id");
                        Bundle bundle = new Bundle();
                        bundle.putString("order_id", orderId);
                        totalFee = totalMoney;
                        productInfo = tv_name.getText().toString();
                        Dlog.e(tv_name.getText().toString() + "GG支付数据" + totalMoney);
                        if ("1".equals(payment_method)) {
                            WxPaymentUtils wxPaymentUtils = new WxPaymentUtils(ShoppingPaymentActivity.this, orderId);
                            wxPaymentUtils.payment();
                            finish();
                        } else {
                            forward(DistributionDetailActivity.class, bundle);
                        }

                    } else {
                        toast("提交失败");
                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {

                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {
                    hideCustomLoadBar();
                }
            });
        }

    }
}
